package io.finer.erp.jeecg.finance.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.ObjectValueUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import io.finer.erp.jeecg.bas.entity.BasBankAccount;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasCustomerAddress;
import io.finer.erp.jeecg.bas.entity.SalesDelivery;
import io.finer.erp.jeecg.bas.entity.SalesDeliveryEntry;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.service.IBasBankAccountService;
import io.finer.erp.jeecg.bas.service.IBasCustomerAddressService;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.ISalesDeliveryEntryService;
import io.finer.erp.jeecg.bas.service.ISalesDeliveryService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.impl.ZrkDeliverEntryServiceImpl;
import io.finer.erp.jeecg.bas.vo.SalesDeliveryOrEntryVO;
import io.finer.erp.jeecg.finance.dto.DeliveryDTO;
import io.finer.erp.jeecg.finance.dto.FinaReceiptAddDto;
import io.finer.erp.jeecg.finance.dto.FinaReceiptDto;
import io.finer.erp.jeecg.finance.dto.FinaReceiptPrintDTO;
import io.finer.erp.jeecg.finance.dto.ZrkShoporderDto;
import io.finer.erp.jeecg.finance.entity.FinaNvoice;
import io.finer.erp.jeecg.finance.entity.FinaReceipt;
import io.finer.erp.jeecg.finance.entity.FinaReceiptEntryLk;
import io.finer.erp.jeecg.finance.mapper.FinaNvoiceMapper;
import io.finer.erp.jeecg.finance.mapper.FinaReceiptMapper;
import io.finer.erp.jeecg.finance.service.IFinaReceiptEntryLkService;
import io.finer.erp.jeecg.finance.service.IFinaReceiptService;
import io.finer.erp.jeecg.finance.vo.DeliverDetalidVO;
import io.finer.erp.jeecg.finance.vo.DeliverySumVO;
import io.finer.erp.jeecg.finance.vo.DeliverySummaryVO;
import io.finer.erp.jeecg.finance.vo.FinaReceiptPage;
import io.finer.erp.jeecg.finance.vo.FinaReceiptPageSumVO;
import io.finer.erp.jeecg.finance.vo.FinaReceiptSKVo;
import io.finer.erp.jeecg.finance.vo.FinaReceiptSumPage;
import io.finer.erp.jeecg.finance.vo.FinaReceiptSumVO;
import io.finer.erp.jeecg.finance.vo.FinaReceiptVO;
import io.finer.erp.jeecg.finance.vo.ReceiptSumVO;
import io.finer.erp.jeecg.finance.vo.ReceiptVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;

/**
 * @Description: 收款表
 * @Author: jeecg-boot
 * @Date:   2021-03-22
 * @Version: V1.0
 */
@Service
public class FinaReceiptServiceImpl extends ServiceImpl<FinaReceiptMapper, FinaReceipt> implements IFinaReceiptService {
    @Autowired
    private FinaReceiptMapper finaReceiptMapper;
    @Autowired
    private IBasCustomerService customerService;
    @Autowired
    private IZrkShoporderService shoporderService;
    @Autowired
    private ISalesDeliveryService deliveryService;
    @Autowired
    private ISalesDeliveryEntryService entryService;
    @Autowired
    private ISysBaseAPI sysBasApi;
	@Autowired
	private IBasCustomerAddressService addressService;
	@Autowired
	private ISalesDeliveryEntryService deliveryEntryService;
	@Autowired
	private IFinaReceiptEntryLkService entryLkService;
	@Autowired
	private IBasBankAccountService accountService;
	@Autowired
	private FinaNvoiceMapper finaNvoiceMapper;


    @Override
    public  List<FinaReceiptPage> getPageReceipt(FinaReceiptVO vo) {
    	String customerName = "";
    	if(oConvertUtils.isNotEmpty(vo.getCustomerName())) {
    		customerName = vo.getCustomerName().trim();
    	}
    	List<FinaReceiptPage> finaReceiptPagePage = finaReceiptMapper.getReceiptPage(vo.getCreateTimeStart(),
        		vo.getCreateTimeEnd(), customerName,
        		vo.getReceivablesEnd(), vo.getReceivablesStart(),
                vo.getReceivedsEnd(), vo.getReceivedsStart(),
                vo.getDiscountSumPriceEnd(), vo.getDiscountSumPriceStart(),
                vo.getInvoicePriceStart(), vo.getInvoicePriceEnd(), vo.getCashType());
    	List<FinaNvoice> finaNvoiceList = finaNvoiceMapper.getSumInvoiceAndCustomerId(vo.getCreateTimeStart(), vo.getCreateTimeEnd());
//    	Map<String, BigDecimal> map = Maps.newHashMap();
//    	if(finaNvoiceList!=null&&finaNvoiceList.size()>0) {
//    		for(FinaNvoice finaNvoice:finaNvoiceList) {
//    			map.put(finaNvoice.getCustomerId(), finaNvoice.getInvoicePrice());
//    		}
//    	}
    	//获取字典值
        Map<String, String> dictItemMap = getDictMap("cash_type");
        for (FinaReceiptPage record : finaReceiptPagePage) {
            FinaReceiptPage receiptPage = finaReceiptMapper.getTotalOwed(record.getCustomerId(), vo.getCustomerName(), vo.getCreateTimeStart());
            FinaReceiptPage receiptNone = finaReceiptMapper.getNoneInvoice(record.getCustomerId(), customerName, vo.getCreateTimeStart());
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal skPrice = BigDecimal.ZERO;
        	BigDecimal noneInvoice = BigDecimal.ZERO;
            if (receiptPage != null) {
            	skPrice = receiptPage.getReceiveds();
            	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed())) {
            		total = receiptPage.getTotalOwed().subtract(skPrice);
            	}
                record.setTotalOwed(total);//期初欠款
                if(receiptNone!=null) {
                	//判断期初开票不为null
                	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed()) 
                			&& oConvertUtils.isNotEmpty(receiptNone.getCumulativeNoneInvoice())) {
                    	noneInvoice = receiptPage.getTotalOwed().subtract(receiptNone.getCumulativeNoneInvoice());
                	}
                    record.setCumulativeNoneInvoice(noneInvoice);//期初未开票
                }else {
                	record.setCumulativeNoneInvoice(noneInvoice);//期初未开票
                }
            }else {
            	record.setTotalOwed(total);//期初欠款
            }
            //货单金额
            BigDecimal receivables = record.getReceivables()==null?BigDecimal.ZERO:record.getReceivables();
            //当前月或条件查询时间收款金额
            BigDecimal receiveds = record.getReceiveds()==null?BigDecimal.ZERO:record.getReceiveds();
            //当前月或条件查询时间开票金额
            BigDecimal invoicePrice = record.getInvoicePrice()==null?BigDecimal.ZERO:record.getInvoicePrice();
            record.setInvoicePrice(invoicePrice);
            BigDecimal decimal = receivables.add(noneInvoice).subtract(invoicePrice);
            
            record.setNoneInvoicePrice(decimal);//期末未开票金额
            String sumPrice = "0";//折扣金额
            if(oConvertUtils.isNotEmpty(record.getDiscountSumPrice())) {
            	sumPrice = record.getDiscountSumPrice();
            }
            record.setDiscountSumPrice(sumPrice);
            BigDecimal bal = receivables.add(total).subtract(receiveds).subtract(new BigDecimal(sumPrice));
            record.setBalance(bal);//应收余额
            String cashType = record.getCashType();
            if(StringUtils.isNotBlank(cashType)) {
            	String text = dictItemMap.get(cashType);
            	if(null != text) {
            		record.setCustomerCashType(text);
            	}
            }
        }
        String field = vo.getColumn();
        String order = vo.getOrder();
        if(StringUtils.equals(field, "totalOwed")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getTotalOwed));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getTotalOwed).reversed());
            }
        }else if(StringUtils.equals(field, "cumulativeNoneInvoice")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getCumulativeNoneInvoice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getCumulativeNoneInvoice).reversed());
            }
        }else if(StringUtils.equals(field, "receivables")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getReceivables));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getReceivables).reversed());
            }
        }else if(StringUtils.equals(field, "receiveds")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getReceiveds));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getReceiveds).reversed());
            }
        }else if(StringUtils.equals(field, "discountSumPrice")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getDiscountSumPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getDiscountSumPrice).reversed());
            }
        }else if(StringUtils.equals(field, "balance")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getBalance));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getBalance).reversed());
            }
        }else if(StringUtils.equals(field, "invoicePrice")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getInvoicePrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getInvoicePrice).reversed());
            }
        }else if(StringUtils.equals(field, "noneInvoicePrice")) {
        	if(StringUtils.equals(order, "asc")) {
    			finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getNoneInvoicePrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPagePage.sort(Comparator.comparing(FinaReceiptPage::getNoneInvoicePrice).reversed());
            }
        }
        return finaReceiptPagePage;
    }


    @Override
    public  FinaReceiptPageSumVO getPageReceiptSum(
                                                 String createTimeStart, String createTimeEnd,
                                                 String customerName,
                                                 BigDecimal receivablesEnd,
                                                 BigDecimal receivablesStart,
                                                 BigDecimal receivedsEnd,BigDecimal receivedsStart,
                                                 BigDecimal invoicePriceStart,BigDecimal invoicePriceEnd,
                                                 BigDecimal discountSumPriceStart,BigDecimal discountSumPriceEnd) {
    	if(oConvertUtils.isNotEmpty(customerName)) {
    		customerName = customerName.trim();
    	}
    	List<FinaReceiptPage> finaReceiptPagePage = finaReceiptMapper.getReceiptPageSum(createTimeStart,
                createTimeEnd, customerName,
                receivablesEnd,receivablesStart,
                receivedsEnd,receivedsStart,
                invoicePriceStart,invoicePriceEnd,
                discountSumPriceStart,discountSumPriceEnd);

        BigDecimal qc = new BigDecimal("0");
        BigDecimal hk = new BigDecimal("0");
        BigDecimal sk = new BigDecimal("0");
        BigDecimal qk = new BigDecimal("0");
        BigDecimal ye = new BigDecimal("0");

        FinaReceiptPageSumVO sumPage=new FinaReceiptPageSumVO();
        for (FinaReceiptPage record : finaReceiptPagePage) {
            FinaReceiptPage receiptPage = finaReceiptMapper.getTotalOwed(record.getCustomerId(), customerName, createTimeStart);
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal skPrice = BigDecimal.ZERO;
        	BigDecimal noneInvoice = BigDecimal.ZERO;
            if (receiptPage != null) {
            	skPrice = receiptPage.getReceiveds();
            	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed())) {
            		total = receiptPage.getTotalOwed().subtract(skPrice);
            	}
                record.setTotalOwed(total);//期初欠款
                if(oConvertUtils.isNotEmpty(receiptPage.getCumulativeNoneInvoice())) {
                	noneInvoice = receiptPage.getCumulativeNoneInvoice();
            	}
                record.setCumulativeNoneInvoice(noneInvoice);//期初未开票
            }else {
            	record.setTotalOwed(total);//期初欠款
            	record.setCumulativeNoneInvoice(noneInvoice);//期初未开票
            }
            BigDecimal decimal = record.getReceivables().add(record.getCumulativeNoneInvoice()).subtract(record.getInvoicePrice());
            record.setNoneInvoicePrice(decimal);//未开票金额
            BigDecimal bal = record.getReceivables().add(record.getTotalOwed()).subtract(record.getReceiveds()).subtract(new BigDecimal(record.getDiscountSumPrice()));
            record.setBalance(bal);//应收余额

            qc = qc.add(total);
            hk = hk.add(record.getReceivables());
            sk = sk.add(record.getReceiveds());
            ye = ye.add(record.getBalance());
            qk = qk.add(new BigDecimal(record.getDiscountSumPrice()));

        }
        sumPage.setTotalOwed(qc);
        sumPage.setReceivables(hk);
        sumPage.setReceiveds(sk);
        sumPage.setDiscountSumPrice(qk);
        sumPage.setBalance(ye.subtract(qk));
        return sumPage;
    }

    @Override
    public  Page<FinaReceiptSKVo> getPageReceiptSK(IPage<FinaReceiptSKVo> page,
                                                 Date createTimeStart, 
                                                 Date createTimeEnd,
                                                 String customerName,
                                                 String cashType,
                                                 HttpServletRequest request){
    	String orderNo = request.getParameter("orderNo");
    	String clearingForm = request.getParameter("clearingForm");
    	String amountStart = request.getParameter("amountStart");
    	String amountEnd = request.getParameter("amountEnd");
    	String discountStart = request.getParameter("discountStart");
    	String discountEnd = request.getParameter("discountEnd");
    	Map<String, Object> map = Maps.newHashMap();
    	map.put("orderNo", orderNo);
    	map.put("clearingForm", clearingForm);
    	if(StringUtils.isNotBlank(amountStart)) {
    		try {
				BigDecimal decimal = new BigDecimal(amountStart);
				map.put("amountStart", decimal);
			} catch (Exception e) {
				map.put("amountStart", null);
			}
    	}
		if(StringUtils.isNotBlank(amountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(amountEnd);
				map.put("amountEnd", decimal);
			} catch (Exception e) {
				map.put("amountEnd", null);
			}
		}
		if(StringUtils.isNotBlank(discountStart)) {
			try {
				BigDecimal decimal = new BigDecimal(discountStart);
				map.put("discountStart", decimal);
			} catch (Exception e) {
				map.put("discountStart", null);
			}
		}
		if(StringUtils.isNotBlank(discountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(discountEnd);
				map.put("discountEnd", decimal);
			} catch (Exception e) {
				map.put("discountEnd", null);
			}
		}
		String column = request.getParameter("column");
		String order = request.getParameter("order");
		if(StringUtils.isNotBlank(column)) {
			map.put("orderFlag", Boolean.TRUE);
			StringBuffer buffer = new StringBuffer(" order by ");
			if(column.equals("code")) {
				buffer.append(" fr.code ");
			} else if (column.equals("customerName")) {
				buffer.append(" fr.customer_name ");
			}else if (column.equals("clearingForm_dictText")) {
				buffer.append(" fr.clearing_form ");
			}else if (column.equals("receiveTime")) {
				buffer.append(" fr.receive_time ");
			}else if (column.equals("price")) {
				buffer.append(" fr.price ");
			}else if (column.equals("discountPrice")) {
				buffer.append(" fr.discount_price ");
			}else if (column.equals("createTime")) {
				buffer.append(" fr.create_time ");
			}
			
			buffer.append(" ").append(order).append(" ");
			map.put("orderStr", buffer.toString());
		} else {
			map.put("orderFlag", Boolean.FALSE);
		}
    	
        Page<FinaReceiptSKVo> finaReceiptPagePage= finaReceiptMapper
        		.getReceiptSKPage(page, createTimeStart, createTimeEnd
        		, customerName, cashType, map);
        List<FinaReceiptSKVo> records = finaReceiptPagePage.getRecords();
        Map<String, String> dictItemMap = getDictMap("cash_type");
        if(CollUtil.isNotEmpty(records)) {
        	List<String> receiptIdList = Lists.newArrayList();
        	for (FinaReceiptSKVo record : records) {
        		String receiptId = record.getId();
        		receiptIdList.add(receiptId);
                String caType = record.getCashType();
                if(StringUtils.isNotBlank(caType)) {
                	String text = dictItemMap.get(caType);
                	record.setCustomerCashType(text);
                }
            }
        	receiptIdList.add(UUID.randomUUID().toString());
        	List<FinaReceiptEntryLk> lkList = this.entryLkService.lambdaQuery().in(FinaReceiptEntryLk::getReceiptId, receiptIdList).list();
        	if(CollUtil.isNotEmpty(lkList)) {
        		Map<String, BigDecimal> hxPriceMap = Maps.newHashMap();
        		for (FinaReceiptEntryLk lk : lkList) {
					BigDecimal amount = lk.getAmount();
					String receiptId = lk.getReceiptId();
					BigDecimal bigDecimal = hxPriceMap.get(receiptId);
					if(null == bigDecimal) {
						if(null != amount) {
							hxPriceMap.put(receiptId, amount);
						} else {
							hxPriceMap.put(receiptId, BigDecimal.ZERO);
						}
					} else {
						if(null != amount) {
							bigDecimal = bigDecimal.add(amount);
							hxPriceMap.put(receiptId, bigDecimal);
						}
					}
				}
        		for (FinaReceiptSKVo record : records) {
        			String id = record.getId();
        			BigDecimal decimal = hxPriceMap.get(id);
        			if(null == decimal) {
        				record.setHxPrice(BigDecimal.ZERO);
        			} else {
        				record.setHxPrice(decimal);
        			}
        		}
        	}
        }
        
        return finaReceiptPagePage;
    }
    
    @Override
    public List<FinaReceiptSKVo> excelGet(Date createTimeStart, Date createTimeEnd, String customerName){
    	return this.baseMapper.excelGet(createTimeStart, createTimeEnd, customerName);
    }

    
    @Override
    public  Page<FinaReceiptSumPage> getPageReceiptSumPage(IPage<FinaReceiptSumPage> page,
                                                 String createTimeStart, String createTimeEnd,
                                                 String customerName){
        Page<FinaReceiptSumPage> finaReceiptPagePage= finaReceiptMapper.getReceiptSumPage(page,createTimeStart,createTimeEnd,customerName);
        return finaReceiptPagePage;
    }

    @Override
    public  Map<String, Object> getDeliveryOrEntry  (String receiptType,String customerId,String createTimeStart,String endTime,
             Integer salesType,String code,String productName,
             Integer viceQtyStart,Integer viceQtyEnd,BigDecimal qtyStart,
             BigDecimal qtyEnd,BigDecimal unitPriceStart,BigDecimal unitPriceEnd,
             BigDecimal totalPriceStart,BigDecimal totalPriceEnd,BigDecimal totalAmountStart,
             BigDecimal totalAmountEnd,BigDecimal hxPriceStart,BigDecimal hxPriceEnd,
             BigDecimal zkPriceStart,BigDecimal zkPriceEnd,BigDecimal qkPriceStart,
             BigDecimal qkPriceEnd,String remark) {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar c = Calendar.getInstance();  
    	if(StringUtils.equals(receiptType, "1")) {
    		List<SalesDeliveryOrEntryVO> list = this.baseMapper.getDeliveryQkPrice(customerId,createTimeStart,endTime
                    ,salesType,code,productName,viceQtyStart,viceQtyEnd,qtyStart,
                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
                    qkPriceEnd,remark);
            return getDeliver(list, customerId, createTimeStart, receiptType);
    	}
    	else if(StringUtils.equals(receiptType, "2")) {
    		List<SalesDeliveryOrEntryVO> list = this.baseMapper.getDeliveryReceivables(customerId,createTimeStart,endTime
                    ,salesType,code,productName,viceQtyStart,viceQtyEnd,qtyStart,
                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
                    qkPriceEnd,remark);
            return getDeliver(list, customerId, createTimeStart, receiptType);
    	}
//    	else if(StringUtils.equals(receiptType, "3")) {
//    		List<SalesDeliveryOrEntryVO> list = this.baseMapper.getDeliveryReceivables(customerId,createTimeStart,endTime
//                    ,salesType,code,productName,viceQtyStart,viceQtyEnd,qtyStart,
//                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
//                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
//                    qkPriceEnd,remark);
//            return getDeliver(list, customerId, createTimeStart, receiptType);
//    	}
    	else {
    		List<SalesDeliveryOrEntryVO> list = this.baseMapper.getDeliveryOrEntry(customerId,createTimeStart,endTime
                    ,salesType,code,productName,viceQtyStart,viceQtyEnd,qtyStart,
                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
                    qkPriceEnd,remark);
            return getDeliver(list, customerId, createTimeStart, receiptType);
    	}
    }

    private Map<String,Object> getDeliver(List<SalesDeliveryOrEntryVO> list,String customerId,String createTimeStart, String receiptType){
    	Map<String, String> dictItemMap = getDictMap("salesType");
        if(CollUtil.isNotEmpty(list)) {
        	for (SalesDeliveryOrEntryVO vo : list) {
				Integer type = vo.getSalesType();
				if(null != type) {
					String text = dictItemMap.get(type.toString());
					if(null != text) {
						vo.setSalesType_dictText(text);
					}
				}
			}
        }

        /********************去除list中code重复的数据*****************************/
        ArrayList<SalesDeliveryOrEntryVO> newList = list.stream().collect
                (Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(SalesDeliveryOrEntryVO::getCode))), ArrayList::new));
        /*********************************************************************/
        FinaReceiptPage receiptPage = finaReceiptMapper.getTotalOwed(customerId,null, createTimeStart);
        SalesDeliveryOrEntryVO entryVO = new SalesDeliveryOrEntryVO();
        entryVO.setProductName("期初欠款");
//        list.add(0,entryVO);
        BigDecimal owed = receiptPage.getTotalOwed()==null?BigDecimal.ZERO:receiptPage.getTotalOwed();
        BigDecimal decimal = owed.subtract(receiptPage.getReceiveds());
        if (receiptPage != null) {
            entryVO.setQkPrice(decimal);//期初欠款
        }
        BigDecimal vq = new BigDecimal("0");
        BigDecimal qty = new BigDecimal("0");
        BigDecimal tp = new BigDecimal("0");
        BigDecimal hp = new BigDecimal("0");
        List<String> codeList = Lists.newArrayList();
        if(StringUtils.equals(receiptType, "1")) {
        	decimal = BigDecimal.ZERO;
        	entryVO.setQkPrice(decimal);
        	BigDecimal zk = BigDecimal.ZERO;//折扣金额
        	for (SalesDeliveryOrEntryVO orEntryVO : list) {
                if( orEntryVO.getHxPrice() != null && orEntryVO.getHxPrice().compareTo(BigDecimal.ZERO)>0){
                    hp=hp.add(orEntryVO.getHxPrice());
                }
                if(orEntryVO.getViceQty() != null && orEntryVO.getViceQty().compareTo(BigDecimal.ZERO)>0){
                    vq=vq.add(orEntryVO.getViceQty());
                }
                if(orEntryVO.getQty() != null && orEntryVO.getQty().compareTo(BigDecimal.ZERO)>0){
                    qty=qty.add(orEntryVO.getQty());
                }
                if(orEntryVO.getTotalPrice() != null && orEntryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
                    tp=tp.add(orEntryVO.getTotalPrice());
                }

                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)&&orEntryVO.getTotalPrice() != null){
                	decimal=decimal.add(orEntryVO.getTotalPrice());
                    orEntryVO.setQkPrice(decimal);
                }
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(1)){
//                	decimal=decimal.subtract(orEntryVO.getHxPrice());
//                    orEntryVO.setQkPrice(decimal);
//                }
            }
        }
//        else if(StringUtils.equals(receiptType, "2")) {
//        	decimal = BigDecimal.ZERO;
//        	for (SalesDeliveryOrEntryVO orEntryVO : list) {
//        		BigDecimal tpce = BigDecimal.ZERO;//货单金额
//        		if(!codeList.contains(orEntryVO.getCode())) {
//        			decimal=decimal.subtract(orEntryVO.getZkPrice());
//        		}
//        		if(oConvertUtils.isNotEmpty(orEntryVO.getTotalAmount())) {
//        			tpce = orEntryVO.getTotalAmount();
//        		}
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
//                    orEntryVO.setHxPrice(new BigDecimal("0"));
//                }
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(1) && orEntryVO.getHxPrice() != null && orEntryVO.getHxPrice().compareTo(BigDecimal.ZERO)>0){
//                    hp=hp.add(orEntryVO.getHxPrice());
//                }
//                if(orEntryVO.getViceQty() != null && orEntryVO.getViceQty().compareTo(BigDecimal.ZERO)>0){
//                    vq=vq.add(orEntryVO.getViceQty());
//                }
//                if(orEntryVO.getQty() != null && orEntryVO.getQty().compareTo(BigDecimal.ZERO)>0){
//                    qty=qty.add(orEntryVO.getQty());
//                }
//                if(orEntryVO.getTotalPrice() != null && orEntryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
//                    tp=tp.add(orEntryVO.getTotalPrice());
//                }
//
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
////                    decimal=decimal.add(orEntryVO.getTotalPrice());
//                    orEntryVO.setQkPrice(orEntryVO.getTotalPrice());
//                }
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(1)){
////                    decimal=decimal.subtract(orEntryVO.getHxPrice().add(orEntryVO.getZkPrice()));
//                    orEntryVO.setQkPrice(orEntryVO.getHxPrice().add(orEntryVO.getZkPrice()));
//                }
//                if(!codeList.contains(orEntryVO.getCode())) {
//                	decimal = decimal.add(tpce);
//        		}
//                codeList.add(orEntryVO.getCode());
//            }
//        }else if(StringUtils.equals(receiptType, "3")) {
//        	for (SalesDeliveryOrEntryVO orEntryVO : list) {
//        		BigDecimal tpce = BigDecimal.ZERO;//货单金额
//        		BigDecimal hxPrice = BigDecimal.ZERO;//收款金额
//        		BigDecimal zkPrice = BigDecimal.ZERO;//折扣金额
//        		if(oConvertUtils.isNotEmpty(orEntryVO.getTotalAmount())) {
//        			tpce = orEntryVO.getTotalAmount();
//        		}
//        		if(oConvertUtils.isNotEmpty(orEntryVO.getHxPrice())) {
//        			hxPrice = orEntryVO.getHxPrice();
//        		}
//        		if(oConvertUtils.isNotEmpty(orEntryVO.getZkPrice())) {
//        			zkPrice = orEntryVO.getZkPrice();
//        		}
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
//                    orEntryVO.setHxPrice(new BigDecimal("0"));
//                }
//
//                if( orEntryVO.getHxPrice() != null && orEntryVO.getHxPrice().compareTo(BigDecimal.ZERO)>0){
//                    hp=hp.add(orEntryVO.getHxPrice());
//                }
//                if(orEntryVO.getViceQty() != null && orEntryVO.getViceQty().compareTo(BigDecimal.ZERO)>0){
//                    vq=vq.add(orEntryVO.getViceQty());
//                }
//                if(orEntryVO.getQty() != null && orEntryVO.getQty().compareTo(BigDecimal.ZERO)>0){
//                    qty=qty.add(orEntryVO.getQty());
//                }
//                if(orEntryVO.getTotalPrice() != null && orEntryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
//                    tp=tp.add(orEntryVO.getTotalPrice());
//                }
//
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
////                    decimal=decimal.add(orEntryVO.getTotalPrice());
//                    orEntryVO.setQkPrice(orEntryVO.getTotalPrice());
//                }
//                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(1)){
////                    decimal=decimal.subtract(orEntryVO.getHxPrice().add(orEntryVO.getZkPrice()));
//                    orEntryVO.setQkPrice(orEntryVO.getTotalPrice());
//                }
//                if(!codeList.contains(orEntryVO.getCode())) {
//                	decimal = decimal.add(tpce).subtract(hxPrice).subtract(zkPrice);
//        		}
//                codeList.add(orEntryVO.getCode());
//            }
//        }
        else {
        	BigDecimal dj = BigDecimal.ZERO;//单据金额
        	for (SalesDeliveryOrEntryVO orEntryVO : list) {
        		if(!codeList.contains(orEntryVO.getCode()) && orEntryVO.getSalesType().equals(0)) {
        			decimal=decimal.subtract(orEntryVO.getZkPrice());
        		}
                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
                    orEntryVO.setHxPrice(new BigDecimal("0"));
                }

                if( orEntryVO.getHxPrice() != null && !codeList.contains(orEntryVO.getCode())){
                    hp=hp.add(orEntryVO.getHxPrice());
                }
                if(orEntryVO.getViceQty() != null && orEntryVO.getViceQty().compareTo(BigDecimal.ZERO)>0){
                    vq=vq.add(orEntryVO.getViceQty());
                }
                if(orEntryVO.getQty() != null && orEntryVO.getQty().compareTo(BigDecimal.ZERO)>0){
                    qty=qty.add(orEntryVO.getQty());
                }
                if(orEntryVO.getTotalPrice() != null && orEntryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
                    tp=tp.add(orEntryVO.getTotalPrice());
                }

                if(orEntryVO.getSalesType()!=null && orEntryVO.getSalesType().equals(0)){
                    decimal=decimal.add(orEntryVO.getTotalPrice());
                    orEntryVO.setQkPrice(decimal);
                    dj = orEntryVO.getTotalAmount();
                }
                if(orEntryVO.getSalesType().equals(1)) {
                    decimal=decimal.subtract(orEntryVO.getHxPrice());
                    orEntryVO.setTotalAmount(dj);
                    orEntryVO.setQkPrice(decimal);
                }
                codeList.add(orEntryVO.getCode());
            }
        }
        SalesDeliveryOrEntryVO entryVO1 = new SalesDeliveryOrEntryVO();
        String date="";
        if(StringUtils.isNotBlank(createTimeStart)) {
            StringBuffer buffer = new StringBuffer();
            String[] s = createTimeStart.split("-");
            buffer.append(s[0]);
            buffer.append("年");
            buffer.append(s[1]);
            buffer.append("月");
            date = buffer.toString();
        }else{
            date=DateUtils.formatDate(new Date(),"yyyy年MM月");
        }


        entryVO1.setProductName(date+"合计");
        entryVO1.setTotalPrice(tp);
        entryVO1.setHxPrice(hp);
//        list.add(list.size(),entryVO1);
        /**集合最后一个位置数据添加*/

        SalesDeliveryOrEntryVO entryVO2 = new SalesDeliveryOrEntryVO();
        entryVO2.setCode("单据数:"+newList.size());
        entryVO2.setProductName("总合计");
        entryVO2.setViceQty(vq);
        entryVO2.setQty(qty);
        entryVO2.setTotalPrice(tp);
        entryVO2.setHxPrice(hp);
        entryVO2.setQkPrice(decimal);
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("total", entryVO2);//合计
        list.add(0, entryVO);//初期欠款
        map.put("settlement", entryVO);//收款信息
        map.put("list", list);//列表
//        list.add(list.size(),entryVO2);
    	return map;
    }

    @Override
    @Transactional
    public boolean marchFlat(FinaReceipt finaReceipt){
        //查询该客户下的所有应收
        LambdaQueryWrapper<FinaReceipt> wrapper = new LambdaQueryWrapper<FinaReceipt>();
        wrapper.eq(FinaReceipt::getCustomerId, finaReceipt.getCustomerId());
        wrapper.eq(FinaReceipt::getBillType, 1);
        wrapper.gt(FinaReceipt::getPrice, 0);
        List<FinaReceipt> receipts = list(wrapper);
        if (receipts != null && receipts.size() > 0) {
            BigDecimal s = finaReceipt.getPrice();
            for (FinaReceipt receipt : receipts) {
                BigDecimal zk = new BigDecimal("0");
                if(finaReceipt.getDiscountPrice().compareTo(BigDecimal.ZERO)>0){
                    zk=finaReceipt.getDiscountPrice();
                }
                BigDecimal rep = receipt.getPrice().add(zk);
                //已收减去应收
                s = s.subtract(rep);
                if (s.compareTo(BigDecimal.ZERO) < 0) {
                    //如果已收减去应收小于零。则将已收减去。
                    receipt.setPrice(s.setScale(2, BigDecimal.ROUND_DOWN).abs());
                    receipt.setHxType("1");
                    updateById(receipt);
                    break;
                } else if (s.compareTo(BigDecimal.ZERO) > 0) {
                    //如果已收减去应收大于0，则将应收改为平账并且继续对其他应收进行平账
                    receipt.setPrice(BigDecimal.ZERO);
                    receipt.setHxType("2");
                    updateById(receipt);
                }else{
                    receipt.setPrice(BigDecimal.ZERO);
                    receipt.setHxType("2");
                    updateById(receipt);
                    break;
                }
            }
        }

        return true;
    }

    @Override
    @Transactional
    public void createReceivables(StkIoBill stkIoBill, List<StkIoBillEntry> stkIoBillEntryList) {
        BigDecimal amt = new BigDecimal(0);
        for(StkIoBillEntry entry : stkIoBillEntryList) {
            amt = amt.add(entry.getSettleAmt());
        }
        FinaReceipt receipt=new FinaReceipt();
        receipt.setBillType("1");//应收
        receipt.setPrice(amt);//金额
        receipt.setCustomerId(stkIoBill.getCustomerId());//客户id
        BasCustomer basCustomer=customerService.getById(stkIoBill.getCustomerId());
        if(basCustomer!=null){
            receipt.setCustomerName(basCustomer.getName());//客户名称
        }
        String code = this.sysBasApi.getNoByCode("cw_ys_no");//财务应收编码
        receipt.setCode(code);
        receipt.setNoneInvoicePrice(amt);//未开票金额
        receipt.setShordorderId(stkIoBill.getSourceId());
        receipt.setBillNo(stkIoBill.getBillNo());
        receipt.setOrderNo(stkIoBill.getSourceNo());
        save(receipt);

    }


    @Override
    @Transactional
    public void createReceivables1(SalesDelivery salesDelivery,List<SalesDeliveryEntry> entries) {

        FinaReceipt receipt=new FinaReceipt();
        receipt.setBillType("1");//应收
        receipt.setCustomerId(salesDelivery.getCustomerId());
        receipt.setCustomerName(salesDelivery.getCustomerName());
        receipt.setPrice(salesDelivery.getTotalAmount());
        receipt.setOrderNo(salesDelivery.getCode());
        receipt.setNoneInvoicePrice(salesDelivery.getTotalAmount());
        String code = this.sysBasApi.getNoByCode("cw_ys_no");//财务应收编码
        receipt.setCode(code);
        save(receipt);
    }



    @Override
    public List<FinaReceiptDto> getReceiptExcel(String createTimeStart, String createTimeEnd,
                                                String customerName){
         List<FinaReceiptDto> list= finaReceiptMapper.getReceiptExcel(createTimeStart,createTimeEnd,customerName);
        for (FinaReceiptDto record : list) {
            record.setBalance(record.getReceivables().subtract(record.getReceiveds()));
            record.setNoneInvoicePrice(record.getReceiveds().subtract(record.getInvoicePrice()));
        }
        return list;
    }


    @Override
    public FinaReceiptSumVO getamountSK(Date createTimeStart, Date createTimeEnd,
                                        String customerName, String cashType
                                        , HttpServletRequest request){
    	Map<String, Object> map = Maps.newHashMap();
    	String orderNo = request.getParameter("orderNo");
    	String clearingForm = request.getParameter("clearingForm");
    	String amountStart = request.getParameter("amountStart");
    	String amountEnd = request.getParameter("amountEnd");
    	String discountStart = request.getParameter("discountStart");
    	String discountEnd = request.getParameter("discountEnd");
    	map.put("orderNo", orderNo);
    	map.put("clearingForm", clearingForm);
    	if(StringUtils.isNotBlank(amountStart)) {
    		try {
				BigDecimal decimal = new BigDecimal(amountStart);
				map.put("amountStart", decimal);
			} catch (Exception e) {
				map.put("amountStart", null);
			}
    	}
		if(StringUtils.isNotBlank(amountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(amountEnd);
				map.put("amountEnd", decimal);
			} catch (Exception e) {
				map.put("amountEnd", null);
			}
		}
		if(StringUtils.isNotBlank(discountStart)) {
			try {
				BigDecimal decimal = new BigDecimal(discountStart);
				map.put("discountStart", decimal);
			} catch (Exception e) {
				map.put("discountStart", null);
			}
		}
		if(StringUtils.isNotBlank(discountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(discountEnd);
				map.put("discountEnd", decimal);
			} catch (Exception e) {
				map.put("discountEnd", null);
			}
		}
        return finaReceiptMapper.getAmount(createTimeStart, createTimeEnd, customerName, cashType, map);
    }

    @Override
    public ReceiptSumVO getamountSum(String createTimeStart, String createTimeEnd,
                                     String customerName){
        return finaReceiptMapper.getAmountSum(createTimeStart, createTimeEnd,customerName);
    }


    @Override
    public List<ZrkShoporderDto> getOrder(ZrkShoporderDto finaReceipt){
        List<ZrkShoporderDto> list=  finaReceiptMapper.getOrderByHxStatus(finaReceipt.getCustomerId());
        BigDecimal decimal=new BigDecimal("0");
        for (ZrkShoporderDto dto : list) {
            dto.setHxPrice(dto.getHxPrice());//已核销金额
            if("1".equals(dto.getHxStatus())){
                BigDecimal subtract=dto.getOrderMoney().subtract(dto.getHxPrice());
                decimal=decimal.add(subtract);
                dto.setOrderMoney(decimal);
            }else{
                decimal=decimal.add(dto.getOrderMoney());
            }
            dto.setAccumulatedPrice(decimal);
        }
        return list;
    }

    @Override
    public List<ZrkShoporderDto> getOrderY(ZrkShoporderDto finaReceipt){
        List<ZrkShoporderDto> list=  finaReceiptMapper.getOrderByHxStatusY(finaReceipt.getCustomerId());
        BigDecimal decimal=new BigDecimal("0");
        for (ZrkShoporderDto dto : list) {
            dto.setHxPrice(dto.getOrderMoney());//已核销金额
            if("1".equals(dto.getHxStatus())){
                BigDecimal subtract=dto.getOrderMoney().subtract(dto.getHxPrice());
                decimal=decimal.add(subtract);
                dto.setOrderMoney(decimal);
            }else{
                decimal=decimal.add(dto.getOrderMoney());
            }
            dto.setAccumulatedPrice(decimal);
        }
        return list;
    }

    @Override
    @Transactional
    public boolean  automaticWriteOff(FinaReceiptAddDto finaReceipt){
    	//TODO
        if(finaReceipt != null&&finaReceipt.getList().size()>0){
            for (ZrkShoporderDto orderId : finaReceipt.getList()) {
                String id=orderId.getOrderNo();
                SalesDelivery delivery= deliveryService.getDeliveryByCode(id);
                BigDecimal finaPrice=finaReceipt.getPrice().add(finaReceipt.getDiscountPrice());
                BigDecimal decimal=finaPrice.subtract(delivery.getTotalAmount());
                ZrkShoporder shoporder=shoporderService.selectByOrderCode(delivery.getCode());
                if(decimal.compareTo(BigDecimal.ZERO) > 0){
                    //如果收款金额减去订单金额>0则该销售单完成核销。继续对后面的销售单进行对比
                    //发货单状态添加
                    delivery.setHxType("2");
                    delivery.setHxId(finaReceipt.getId());
                    delivery.setHxPrice(delivery.getTotalAmount());
                    deliveryService.updateById(delivery);
                    //销售订单状态添加
                    shoporder.setHxPrice(decimal.toString());
                    shoporder.setOrderHxStatus("2");
                    shoporder.setHxId(finaReceipt.getId());
                    shoporderService.updateById(shoporder);
                }else if(decimal.compareTo(BigDecimal.ZERO) < 0){
                    //如果收款金额减去订单金额<0则该销售单状态改为部分核销。并结束对后面销售单的对比
                    //发货单状态添加
                    delivery.setHxType("1");
                    delivery.setHxId(finaReceipt.getId());
                    delivery.setHxPrice(decimal);
                    deliveryService.updateById(delivery);
                    //销售订单状态添加
                    shoporder.setHxPrice(decimal.toString());
                    shoporder.setOrderHxStatus("1");
                    shoporder.setHxId(finaReceipt.getId());
                    shoporderService.updateById(shoporder);
                    break;
                }else{
                    //如果收款金额减去订单金额==0则该销售单的状态改为完成核销。并结束对比
                    //发货单状态添加
                    delivery.setHxType("2");
                    delivery.setHxId(finaReceipt.getId());
                    delivery.setHxPrice(delivery.getTotalAmount());
                    deliveryService.updateById(delivery);
                    //销售订单状态添加
                    shoporder.setHxPrice(decimal.toString());
                    shoporder.setOrderHxStatus("2");
                    shoporder.setHxId(finaReceipt.getId());
                    shoporderService.updateById(shoporder);
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public List<DeliverySummaryVO> getDeliver(DeliverySummaryVO summaryVO){
        String[] str=null;
        if(StringUtils.isNotBlank(summaryVO.getCategoryIds())) {
            str = summaryVO.getCategoryIds().split(",");
        }
        String field = summaryVO.getColumn();
        String order = summaryVO.getOrder();
        List<DeliverySummaryVO> list=finaReceiptMapper.getDelivers(summaryVO.getCreateTimeStart(),summaryVO.getCreateTimeEnd(), str);
        DeliverySumVO sum=finaReceiptMapper.getDeliverSum(summaryVO.getCreateTimeStart(),summaryVO.getCreateTimeEnd(),str);
        BigDecimal qtySum = BigDecimal.ZERO;//数量总和
        BigDecimal priceSum = BigDecimal.ZERO;//总金额总和
        for (DeliverySummaryVO deliverySummaryVO : list) {
        	try {
				ObjectValueUtils.getObjectValue(deliverySummaryVO);
			} catch (Exception e) {
				e.printStackTrace();
			}
            if(deliverySummaryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
                BigDecimal  decimal = deliverySummaryVO.getTotalPrice().divide(deliverySummaryVO.getQty(), 4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                deliverySummaryVO.setAverageUnitPrice(decimal);
                BigDecimal dec=deliverySummaryVO.getTotalPrice().divide(sum.getPriceSum(),4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                dec=dec.multiply(new BigDecimal("100"));
                deliverySummaryVO.setPriceRatio(dec+"%");
                priceSum = priceSum.add(deliverySummaryVO.getTotalPrice());
            }
            if(deliverySummaryVO.getQty().compareTo(BigDecimal.ZERO)>0){
                BigDecimal dec=deliverySummaryVO.getQty().divide(sum.getQtySum(),4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                dec=dec.multiply(new BigDecimal("100"));
                deliverySummaryVO.setQtyRatio(dec+"%");
                qtySum = qtySum.add(deliverySummaryVO.getQty());
            }
        }
//        if(StringUtils.equals(field, "qtyRatio")) {
//    		if(StringUtils.equals(order, "asc")) {
//    			list.sort(Comparator.comparing(DeliverySummaryVO::getQtyRatio));
//            }else if(StringUtils.equals(order, "desc")) {
//            	list.sort(Comparator.comparing(DeliverySummaryVO::getQtyRatio).reversed());
//            }
//    	}else if(StringUtils.equals(field, "priceRatio")) {
//    		if(StringUtils.equals(order, "asc")) {
//    			list.sort(Comparator.comparing(DeliverySummaryVO::getPriceRatio));
//            }else if(StringUtils.equals(order, "desc")) {
//            	list.sort(Comparator.comparing(DeliverySummaryVO::getPriceRatio).reversed());
//            }
//    	}else 
    	if(StringUtils.equals(field, "averageUnitPrice")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getAverageUnitPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getAverageUnitPrice).reversed());
            }
    	}else if(StringUtils.equals(field, "qty")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getQty));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getQty).reversed());
            }
    	}else if(StringUtils.equals(field, "unit")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getUnit));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getUnit).reversed());
            }
    	}else if(StringUtils.equals(field, "totalPrice")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getTotalPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getTotalPrice).reversed());
            }
    	}else if(StringUtils.equals(field, "code")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getCode));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getCode).reversed());
            }
    	}else if(StringUtils.equals(field, "categoryName")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(DeliverySummaryVO::getCategoryName));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(DeliverySummaryVO::getCategoryName).reversed());
            }
    	}
    	DeliverySummaryVO deliverySummaryVO = new DeliverySummaryVO();
    	deliverySummaryVO.setCode("合计");
    	deliverySummaryVO.setQty(qtySum);
    	deliverySummaryVO.setTotalPrice(priceSum);
    	list.add(deliverySummaryVO);
        return list;
    }

    @Override
    public DeliverySumVO getDeliverSum(DeliverySumVO sumVO){
        String[] s=null;
        if(StringUtils.isNotBlank(sumVO.getCategoryIds())) {
            s = sumVO.getCategoryIds().split(",");
        }
        DeliverySumVO sum=finaReceiptMapper.getDeliverSum(sumVO.getStartTime(),sumVO.getEndTime(),s);
        return sum;
    }
    @Override
    public  List<DeliverDetalidVO> getDeliverDetali(DeliverDetalidVO detalidVO) {
        String[] str1=null;
        if(StringUtils.isNotBlank(detalidVO.getCustomerIds())){
            str1 = detalidVO.getCustomerIds().split(",");
        }
        List<DeliverDetalidVO> list= finaReceiptMapper.getDeliverDetali(str1,detalidVO.getCreateTimeStart(),detalidVO.getCreateTimeEnd(),detalidVO.getCategoryName());
        List<DeliverDetalidVO> voList = Lists.newArrayList();
        List<String> customerIdList = Lists.newArrayList();
        DeliverDetalidVO vo = new DeliverDetalidVO();
        vo.setUnitPrice(BigDecimal.ZERO);
        vo.setSumPrice(BigDecimal.ZERO);
        vo.setViceQty(BigDecimal.ZERO);
        vo.setQty(BigDecimal.ZERO);
        int i = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (DeliverDetalidVO deliverDetalidVO : list) {
        	++i;
//            BigDecimal decimal = deliverDetalidVO.getSumPrice().divide(deliverDetalidVO.getQty(), 2).setScale(2, BigDecimal.ROUND_DOWN);
//            deliverDetalidVO.setAverageUnitPrice(decimal);
        	
        	if(!customerIdList.contains(deliverDetalidVO.getCustomerId())&&customerIdList!=null&&customerIdList.size()>0) {
        		voList.add(vo);
        		vo = new DeliverDetalidVO();
        		vo.setUnitPrice(BigDecimal.ZERO);
                vo.setSumPrice(BigDecimal.ZERO);
                vo.setViceQty(BigDecimal.ZERO);
                vo.setQty(BigDecimal.ZERO);
        	}
        	if(oConvertUtils.isNotEmpty(deliverDetalidVO.getShippingDate())) {
        		try {
					Date d = format.parse(deliverDetalidVO.getShippingDate());
					deliverDetalidVO.setShippingDate(format.format(d));
				} catch (ParseException e) {
					e.printStackTrace();
				}
        	}
        	vo.setCategoryName("小计");
    		vo.setCustomerName(deliverDetalidVO.getCustomerName());
    		vo.setCustomerId(deliverDetalidVO.getCustomerId());
//    		vo.setUnit(deliverDetalidVO.getUnit());
//    		vo.setUnitPrice(vo.getUnitPrice().add(deliverDetalidVO.getUnitPrice()));
            vo.setSumPrice(vo.getSumPrice().add(deliverDetalidVO.getSumPrice()));
            vo.setViceQty(vo.getViceQty().add(deliverDetalidVO.getViceQty()));
            vo.setQty(vo.getQty().add(deliverDetalidVO.getQty()));
        	customerIdList.add(deliverDetalidVO.getCustomerId());
        	voList.add(deliverDetalidVO);
        	if(list.size()==i) {
        		voList.add(vo);
        	}
        }
        return voList;
    }


    @Override
    public  List<SalesDeliveryEntry> exportDelivery(String code){



        return entryService.getSalesDeliveryEntryList(code);
    }


	@Override
	@Transactional
	public Result<?> addReceipt(FinaReceiptAddDto finaReceipt) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		FinaReceipt receipt = new FinaReceipt();
		BasCustomer basCustomer = customerService.getById(finaReceipt.getCustomerId());
		BasCustomerAddress customAddress = addressService.getCustomAddress(finaReceipt.getCustomerId());
		String cusName = "";
		if (basCustomer != null) {
			cusName = basCustomer.getName();
		}
		finaReceipt.setCustomerName(cusName);
		String code = this.sysBasApi.getNoByCode("cw_sk_no");
		receipt.setPrice(finaReceipt.getPrice());
		if(finaReceipt.getDiscountPrice() == null) {
			finaReceipt.setDiscountPrice(BigDecimal.ZERO);
		}
		receipt.setDiscountPrice(finaReceipt.getDiscountPrice());
		receipt.setAccountId(finaReceipt.getAccountId());
		receipt.setCustomerId(finaReceipt.getCustomerId());
		receipt.setCustomerName(cusName);
		receipt.setClearingForm(finaReceipt.getClearingForm());
		receipt.setCode(code);
		receipt.setBillType("2");
		receipt.setRemark(finaReceipt.getRemark());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		if (StringUtils.isNotBlank(finaReceipt.getReceiveTime())) {
			date = DateUtils.str2Date(finaReceipt.getReceiveTime(), format);
		}
		receipt.setReceiveTime(date);
		this.save(receipt);// 保存收款i想你想
//		 finaReceiptService.marchFlat(receipt);//计算收款核销
		finaReceipt.setId(receipt.getId());
		// 核销销售订单
		automaticWriteOff(finaReceipt);// 核销订单
		SalesDelivery delivery = new SalesDelivery();// 发货单收款信息
		delivery.setCode(code);
		delivery.setHxPrice(finaReceipt.getPrice());
		delivery.setZkPrice(finaReceipt.getDiscountPrice());
		delivery.setCustomerId(finaReceipt.getCustomerId());
		delivery.setCustomerName(cusName);
		delivery.setShippingDate(date);
		delivery.setSalesType(1);
		delivery.setMaker(sysUser.getRealname());
		if (customAddress != null) {
			delivery.setCustomerAddress(customAddress.getAddress());
			delivery.setCustomerPhone(customAddress.getPhoneNo());
		}
		delivery.setHxId(receipt.getId());
		deliveryService.save(delivery);// 添加发货单收款信息
		SalesDeliveryEntry entry = new SalesDeliveryEntry();
		String dictName = sysBasApi.queryDictTextByKey("clearingForm", finaReceipt.getClearingForm());
		entry.setProductName(dictName);
		entry.setCustomerId(delivery.getCustomerId());
		entry.setDeliveryId(delivery.getId());
		deliveryEntryService.save(entry);// 保存发货单收款明细---其实基本就一个结算方式~~

		return Result.ok("添加成功!");
	}


	/**
	 * @Description 获取dict信息
	 * @param dictCode
	 * @return
	 * Create at: 2021-05-25 17:46:54
	 * @author: duany
	 * Revision:
	 *    2021-05-25 17:46:54 - first revision by duany
	 *        
	 */
	private Map<String, String> getDictMap(String dictCode){
		List<DictModel> items = sysBasApi.queryDictItemsByCode(dictCode);
        Map<String, String> dictItemMap = Maps.newHashMap();
        if(CollUtil.isNotEmpty(items)) {
        	for (DictModel model : items) {
        		String value = model.getValue();
        		String text = model.getText();
        		dictItemMap.put(value, text);
			}
        }
        return dictItemMap;
	}


	@Override
	public IPage<SalesDeliveryOrEntryVO> getSalesDeliveryAndEntry(Page<SalesDeliveryOrEntryVO> page, SalesDeliveryOrEntryVO vo) {
		// TODO Auto-generated method stub
		String[] customerIds = null;
		if(oConvertUtils.isNotEmpty(vo.getCustomerIds())) {
			customerIds = vo.getCustomerIds().split(",");
		}
		IPage<SalesDeliveryOrEntryVO> pageList = this.baseMapper.selectSalesDeliveryAndEntry(page, 
				vo.getCustomerName(), vo.getCreateTimeStart(), vo.getCreateTimeEnd(), vo.getSalesType(),
				vo.getCode(), vo.getProductName(), vo.getViceQtyStart(), vo.getViceQtyEnd(), 
				vo.getQtyStart(), vo.getQtyEnd(), vo.getUnitPriceStart(), vo.getUnitPriceEnd(), 
				vo.getTotalPriceStart(), vo.getTotalPriceEnd(), vo.getTotalAmountStart(), vo.getTotalAmountEnd(), 
				vo.getHxPriceStart(), vo.getHxPriceEnd(), vo.getZkPriceStart(), vo.getZkPriceEnd(),
				vo.getQkPriceStart(), vo.getQkPriceEnd(), vo.getRemark(),customerIds);
		if(pageList!=null&&pageList.getSize()>0) {
			//将查到的金额重新赋值到欠款金额
			for(SalesDeliveryOrEntryVO svo:pageList.getRecords()) {
				if(oConvertUtils.isNotEmpty(svo.getCreateBy())) {
					LoginUser user = sysBasApi.getUserByName(svo.getCreateBy());
					String createBy = user.getRealname();
					svo.setCreateBy(createBy);
				}
				if(svo.getSalesType()!=null && svo.getSalesType().equals(0)){
					svo.setQkPrice(svo.getTotalPrice());
                }
                if(svo.getSalesType()!=null && svo.getSalesType().equals(1)){
                	svo.setQkPrice(svo.getHxPrice().add(svo.getZkPrice()));
                }
			}
		}
		return pageList;
	}
	
	@Override
	@Transactional
	public Result<?> addReceipt(ReceiptVO vo) throws JeecgBootException{
		FinaReceipt receipt = new FinaReceipt();
		List<DeliveryDTO> deliveryList = vo.getEntryIdList();
//		if(CollUtil.isEmpty(deliveryList)) {
//			return Result.error("请选择要核销的单据。");
//		}
		List<String> entryIdList = Lists.newArrayList(UUID.randomUUID().toString());
		for (DeliveryDTO deliveryDTO : deliveryList) {
			entryIdList.add(deliveryDTO.getId());
		}
		List<SalesDeliveryEntry> entrys = this.entryService.lambdaQuery().in(SalesDeliveryEntry::getId, entryIdList).list();
//		if(CollUtil.isEmpty(entrys)) {
//			return Result.error("请选择要核销的单据。");
//		}
		BigDecimal entryTotalMoney = BigDecimal.ZERO;
		if(CollUtil.isNotEmpty(entrys)) {
			for(SalesDeliveryEntry entry: entrys) {
				BigDecimal totalPrice = entry.getTotalPrice();
				BigDecimal writeAmount = entry.getWriteAmount();
				if(null == writeAmount) {
					writeAmount = BigDecimal.ZERO;
				}
				entryTotalMoney = entryTotalMoney.add(totalPrice).subtract(writeAmount);
			}
		}
		BigDecimal price = vo.getPrice();
		if(price == null) {
			return Result.error("金额错误");
		}
		if(vo.getDiscountPrice() == null) {
			vo.setDiscountPrice(BigDecimal.ZERO);
		}
		BigDecimal discountPrice = vo.getDiscountPrice();
		
		Map<String, SalesDeliveryEntry> entryMap = Maps.newHashMap();
		List<String> deliveryIdList = Lists.newArrayList(UUID.randomUUID().toString());
		for(SalesDeliveryEntry entry: entrys) {
			entryMap.put(entry.getId(), entry);
			String deliveryId = entry.getDeliveryId();
			if(null == deliveryId) {
				continue;
			}
			if(!deliveryIdList.contains(deliveryId)) {
				deliveryIdList.add(deliveryId);
			}
		}
//		if(CollUtil.isEmpty(deliveryIdList)) {
//			return Result.error("请选择要核销的出库单。");
//		}
		List<SalesDelivery> deliverys = this.deliveryService.lambdaQuery().in(SalesDelivery::getId, deliveryIdList).list();
//		if(CollUtil.isEmpty(deliverys)) {
//			return Result.error("请选择要核销的出库单。");
//		}
		
		String customerId = vo.getCustomerId();
		BasCustomer basCustomer = customerService.getById(customerId);
		String cusName = "";
		if (basCustomer != null) {
			cusName = basCustomer.getName();
		}
		receipt.setCustomerName(cusName);
		String code = this.sysBasApi.getNoByCode("cw_sk_no");
		receipt.setPrice(price);
		receipt.setCode(code);
		receipt.setBillType("2");
		receipt.setIsHx(vo.getIsHX().toString());
		receipt.setInvoicePrice(BigDecimal.ZERO);
		receipt.setCustomerId(customerId);
		receipt.setAccountId(vo.getAccountId());
		String receiveTimeStr = vo.getReceiveTime();
		Date receiveTime = null;
		if(StringUtils.isBlank(receiveTimeStr)) {
			receiveTime = DateUtil.date();
		} else {
			receiveTime = DateUtil.parseDate(receiveTimeStr);
		}
		receipt.setReceiveTime(receiveTime);
		receipt.setDiscountPrice(discountPrice);
		receipt.setClearingForm(vo.getClearingForm());
		receipt.setRemark(vo.getRemark());
		this.save(receipt);
		
		//输入的金额与核销金额对比
		BigDecimal receiptPrice = price.add(discountPrice);
		if(entryTotalMoney.compareTo(BigDecimal.ZERO) > 0) {
			Map<String, SalesDelivery> theDeliveryMap = Maps.newHashMap();
			//给别的单子结算之后剩下的钱数
			BigDecimal residueEntryAmount = NumberUtil.add(BigDecimal.ZERO, receiptPrice);
			boolean flag = false;
			//给每个收货单明细的结算金额和结算状态赋值
			for(SalesDeliveryEntry entry : entrys) {
				BigDecimal totalPrice = entry.getTotalPrice();
				BigDecimal writeAmount = entry.getWriteAmount() == null ? BigDecimal.ZERO : entry.getWriteAmount();
				BigDecimal addAmount = totalPrice.subtract(writeAmount);
				BigDecimal entryPrice = BigDecimal.ZERO;
				if(residueEntryAmount.compareTo(addAmount) > 0) {
					residueEntryAmount = residueEntryAmount.subtract(addAmount);
					entry.setWriteAmount(totalPrice);
					entry.setWriteStatus("2");
					entryPrice = addAmount;
				} else if(residueEntryAmount.compareTo(addAmount) == 0) {
					residueEntryAmount = residueEntryAmount.subtract(addAmount);
					entry.setWriteAmount(totalPrice);
					entry.setWriteStatus("2");
					entryPrice = addAmount;
					flag = true;
				} else {
					entryPrice = residueEntryAmount;
					entry.setWriteStatus("1");
					entry.setWriteAmount(residueEntryAmount.add(writeAmount));
					flag = true;
				}
				this.entryService.updateById(entry);
				
				//添加一条收款单与发货明细的关联信息
				FinaReceiptEntryLk lk = new FinaReceiptEntryLk();
				lk.setEntryId(entry.getId());
				lk.setEntryStatus(entry.getWriteStatus());
				lk.setAmount(entryPrice);
				lk.setDeliveryId(entry.getDeliveryId());
				lk.setReceiptId(receipt.getId());
				this.entryLkService.save(lk);
				
				//发货单的总金额计算
				String deliveryId = entry.getDeliveryId();
				SalesDelivery delivery = theDeliveryMap.get(deliveryId);
				if(null == delivery) {
					delivery = new SalesDelivery();
					delivery.setId(deliveryId);
					delivery.setTotalAmount(entryPrice);
					theDeliveryMap.put(deliveryId, delivery);
				} else {
					BigDecimal totalAmount = delivery.getTotalAmount();
					if(null == totalAmount) {
						totalAmount = BigDecimal.ZERO;
					}
					totalAmount = totalAmount.add(entryPrice);
					delivery.setTotalAmount(totalAmount);
				}
				if(flag) {
					break;
				}
			}
			//遍历发货单，修改发货单的收款状况
			Map<String, SalesDelivery> deliveryMap = Maps.newHashMap();
			if(CollUtil.isNotEmpty(deliverys)) {
				for(SalesDelivery delivery : deliverys) {
					deliveryMap.put(delivery.getId(), delivery);
				}
			}
			//TODO
			for(String key : theDeliveryMap.keySet()) {
				SalesDelivery salesDelivery = deliveryMap.get(key);
				if(null != salesDelivery) {
					String deliveryId = salesDelivery.getId();
					ZrkShoporder shoporder = shoporderService.selectByOrderCode(salesDelivery.getSourceCode());
					if(null == shoporder) {
						throw new JeecgBootException("未找到销售订单" + salesDelivery.getSourceCode());
					}
					List<SalesDeliveryEntry> entryList = deliveryEntryService.lambdaQuery().eq(SalesDeliveryEntry::getDeliveryId, deliveryId).list();
					BigDecimal totalWriteAmount = BigDecimal.ZERO;
					int status0Count = 0;
					int status1Count = 0;
					int status2Count = 0;
					for (SalesDeliveryEntry entry : entryList) {
						String writeStatus = entry.getWriteStatus();
						BigDecimal writeAmount = entry.getWriteAmount();
						if(null == writeStatus) {
							writeStatus = "0";
						}
						if(null == writeAmount) {
							writeAmount = BigDecimal.ZERO;
						}
						totalWriteAmount = totalWriteAmount.add(writeAmount);
						if("2".equals(writeStatus)) {
							status2Count ++;
						}
						if("1".equals(writeStatus)) {
							status1Count ++;
						}
						if("0".equals(writeStatus)) {
							status0Count ++;
						}
					}
					String hxStatus = StringUtils.EMPTY;
					if((status0Count > 0 || status1Count > 0) && status2Count > 0) {
						hxStatus = "1";
					}
					else if(status0Count > 0 && status1Count == 0 && status2Count == 0) {
						hxStatus = "0";
					}
					else if(status0Count == 0 && status1Count > 0 && status2Count == 0) {
						hxStatus = "1";
					}
					else if(status0Count == 0 && status1Count == 0 && status2Count > 0) {
						hxStatus = "2";
					}
					else if(status0Count > 0 && status1Count > 0 && status2Count == 0) {
						hxStatus = "1";
					}
					String receiptId = receipt.getId();
					String deliveryHxId = salesDelivery.getHxId();
					if(StringUtils.isBlank(deliveryHxId)) {
						deliveryHxId = receiptId;
					} else {
						deliveryHxId = deliveryHxId + "," + receiptId;
					}
					salesDelivery.setHxType(hxStatus);
//					BigDecimal deliveryHxPrice = salesDelivery.getHxPrice() == null ? BigDecimal.ZERO : salesDelivery.getHxPrice();
					salesDelivery.setHxPrice(totalWriteAmount);
					salesDelivery.setHxId(deliveryHxId);
					deliveryService.updateById(salesDelivery);
					//销售订单状态添加
					String orderHxId = shoporder.getHxId();
					if(StringUtils.isBlank(orderHxId)) {
						orderHxId = receiptId;
					} else {
						orderHxId = orderHxId + "," + receiptId;
					}
//					String orderHxPriceStr = shoporder.getHxPrice();
//					BigDecimal orderHxPrice = StringUtils.isBlank(orderHxPriceStr) ? BigDecimal.ZERO : new BigDecimal(orderHxPriceStr);
//					orderHxPrice = orderHxPrice.add(totalWriteAmount);
                    shoporder.setHxPrice(totalWriteAmount.toPlainString());
                    shoporder.setOrderHxStatus(hxStatus);
                    shoporder.setHxId(orderHxId);
                    shoporderService.updateById(shoporder);
					this.deliveryService.updateById(salesDelivery);
				}
			}
		}
		
		//添加一个发货单信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		SalesDelivery delivery = new SalesDelivery();// 发货单收款信息
		delivery.setCode(code);
		delivery.setHxPrice(receipt.getPrice());
		delivery.setZkPrice(receipt.getDiscountPrice());
		delivery.setCustomerId(receipt.getCustomerId());
		delivery.setCustomerName(cusName);
		delivery.setShippingDate(receiveTime);
		delivery.setSalesType(1);
		delivery.setMaker(sysUser.getRealname());
		BasCustomerAddress customAddress = addressService.getCustomAddress(customerId);
		if (customAddress != null) {
			delivery.setCustomerAddress(customAddress.getAddress());
			delivery.setCustomerPhone(customAddress.getPhoneNo());
		}
		delivery.setHxId(receipt.getId());
		deliveryService.save(delivery);// 添加发货单收款信息
		SalesDeliveryEntry entry = new SalesDeliveryEntry();
		String dictName = sysBasApi.queryDictTextByKey("clearingForm", receipt.getClearingForm());
		entry.setProductName(dictName);
		entry.setCustomerId(delivery.getCustomerId());
		entry.setDeliveryId(delivery.getId());
		deliveryEntryService.save(entry);// 保存发货单收款明细---其实基本就一个结算方式~~
		
		return Result.ok("添加成功");
	}

	@Override
//	@Transactional
	public Result<?> updateReceipt(ReceiptVO vo) {
		// TODO Auto-generated method stub
		String receiptId = vo.getId();
		//获取原来的单据信息
		//新的单据信息
		FinaReceipt receipt = new FinaReceipt();
		List<FinaReceiptEntryLk> oldLkList = entryLkService.lambdaQuery().eq(FinaReceiptEntryLk::getReceiptId, receiptId).list();
		
		List<DeliveryDTO> deliveryList = vo.getEntryIdList();
//		if(CollUtil.isEmpty(deliveryList)) {
//			return Result.error("请选择要核销的单据。");
//		}
		List<String> entryIdList = Lists.newArrayList(UUID.randomUUID().toString());
		for (DeliveryDTO deliveryDTO : deliveryList) {
			entryIdList.add(deliveryDTO.getId());
		}
		List<SalesDeliveryEntry> entrys = this.entryService.lambdaQuery().in(SalesDeliveryEntry::getId, entryIdList).list();
//		if(CollUtil.isEmpty(entrys)) {
//			return Result.error("请选择要核销的单据。");
//		}
		BigDecimal entryTotalMoney = BigDecimal.ZERO;
		for(SalesDeliveryEntry entry: entrys) {
			BigDecimal totalPrice = entry.getTotalPrice();
			BigDecimal writeAmount = entry.getWriteAmount();
			if(null == writeAmount) {
				writeAmount = BigDecimal.ZERO;
			}
			entryTotalMoney = entryTotalMoney.add(totalPrice).subtract(writeAmount);
			for (FinaReceiptEntryLk lk : oldLkList) {
				if(StringUtils.equals(entry.getId(), lk.getEntryId())) {
					BigDecimal amount = lk.getAmount();
					if(null == amount) {
						amount = BigDecimal.ZERO;
					}
					entryTotalMoney = entryTotalMoney.add(amount);
				}
			}
		}
		BigDecimal price = vo.getPrice();
		if(vo.getDiscountPrice() == null) {
			vo.setDiscountPrice(BigDecimal.ZERO);
		}
		BigDecimal discountPrice2 = vo.getDiscountPrice();
		BigDecimal receiptPrice = price.add(discountPrice2);
//		if(entryTotalMoney.compareTo(receiptPrice) < 0) {
//			return Result.error("选择核销的单据金额小于输入的金额。");
//		}
		Map<String, SalesDeliveryEntry> entryMap = Maps.newHashMap();
		List<String> deliveryIdList = Lists.newArrayList(UUID.randomUUID().toString());
		for(SalesDeliveryEntry entry : entrys) {
			entryMap.put(entry.getId(), entry);
			String deliveryId = entry.getDeliveryId();
			if(null == deliveryId) {
				continue;
			}
			if(!deliveryIdList.contains(deliveryId)) {
				deliveryIdList.add(deliveryId);
			}
		}
//		if(CollUtil.isEmpty(deliveryIdList)) {
//			return Result.error("请选择要核销的出库单。");
//		}
		List<SalesDelivery> deliverys = this.deliveryService.lambdaQuery().in(SalesDelivery::getId, deliveryIdList).list();
//		if(CollUtil.isEmpty(deliverys)) {
//			return Result.error("请选择要核销的出库单。");
//		}
		
		//根据LK的信息处理原来的付款信息
		Map<String, SalesDelivery> oldDeliveryMap = Maps.newHashMap();
		List<String> oldLkIdList = Lists.newArrayList();
		List<String> oldEntryIds = Lists.newArrayList(UUID.randomUUID().toString());
		List<String> oldDeleveryIds = Lists.newArrayList(UUID.randomUUID().toString());
		Map<String, FinaReceiptEntryLk> oldLkMap = Maps.newHashMap();
		Map<String, SalesDeliveryEntry> oldEntryMap = Maps.newHashMap();
 		for(FinaReceiptEntryLk lk : oldLkList) {
			oldLkIdList.add(lk.getId());
			oldEntryIds.add(lk.getEntryId());
			oldLkMap.put(lk.getEntryId(), lk);
			oldDeleveryIds.add(lk.getDeliveryId());
		}
		List<SalesDelivery> oldDeliveryList = this.deliveryService.lambdaQuery().in(SalesDelivery::getId, oldDeleveryIds).list();
		if(null != oldDeliveryList) {
			for (SalesDelivery sd : oldDeliveryList) {
				oldDeliveryMap.put(sd.getId(), sd);
			}
		}
		List<SalesDeliveryEntry> oldEntryList = this.entryService.lambdaQuery().in(SalesDeliveryEntry::getId, oldEntryIds).list();
		if(null != oldDeliveryList) {
			for (SalesDeliveryEntry entry : oldEntryList) {
				oldEntryMap.put(entry.getId(), entry);
			}
		}
		for (FinaReceiptEntryLk lk : oldLkList) {
			String entryId = lk.getEntryId();
			BigDecimal amount = lk.getAmount();
			
			SalesDeliveryEntry salesDeliveryEntry = oldEntryMap.get(entryId);
			BigDecimal entryAmount = salesDeliveryEntry.getWriteAmount();
			if(entryAmount.compareTo(amount) > 0) {
				salesDeliveryEntry.setWriteAmount(entryAmount.subtract(amount));
				salesDeliveryEntry.setWriteStatus("1");
			} else {
				salesDeliveryEntry.setWriteAmount(BigDecimal.ZERO);
				salesDeliveryEntry.setWriteStatus("0");
			}
			this.deliveryEntryService.updateWriteAmount(salesDeliveryEntry);
		}
		for(String key : oldDeliveryMap.keySet()) {
			SalesDelivery salesDelivery = oldDeliveryMap.get(key);
			if(null != salesDelivery) {
				String deliveryId = salesDelivery.getId();
				ZrkShoporder shoporder = shoporderService.selectByOrderCode(salesDelivery.getSourceCode());
				List<SalesDeliveryEntry> entryList = deliveryEntryService.lambdaQuery().eq(SalesDeliveryEntry::getDeliveryId, deliveryId).list();
				BigDecimal totalWriteAmount = BigDecimal.ZERO;
				//TODO
				int status0Count = 0;
				int status1Count = 0;
				int status2Count = 0;
				for (SalesDeliveryEntry entry : entryList) {
					String writeStatus = entry.getWriteStatus();
					BigDecimal writeAmount = entry.getWriteAmount();
					if(null == writeStatus) {
						writeStatus = "0";
					}
					if(null == writeAmount) {
						writeAmount = BigDecimal.ZERO;
					}
					totalWriteAmount = totalWriteAmount.add(writeAmount);
					if("2".equals(writeStatus)) {
						status2Count ++;
					}
					if("1".equals(writeStatus)) {
						status1Count ++;
					}
					if("0".equals(writeStatus)) {
						status0Count ++;
					}
				}
				String hxStatus = StringUtils.EMPTY;
				if((status0Count > 0 || status1Count > 0) && status2Count > 0) {
					hxStatus = "1";
				}
				else if(status0Count > 0 && status1Count == 0 && status2Count == 0) {
					hxStatus = "0";
				}
				else if(status0Count == 0 && status1Count > 0 && status2Count == 0) {
					hxStatus = "1";
				}
				else if(status0Count == 0 && status1Count == 0 && status2Count > 0) {
					hxStatus = "2";
				}
				else if(status0Count > 0 && status1Count > 0 && status2Count == 0) {
					hxStatus = "1";
				}
				String deliveryHxId = salesDelivery.getHxId();
				if(StringUtils.isNotBlank(deliveryHxId)) {
					String[] strs = deliveryHxId.split(",");
					List<String> idList = CollUtil.newArrayList(strs);
					for (int i = 0; i < idList.size(); i++) {
						String str = idList.get(i);
						if(str.equals(receiptId)) {
							idList.remove(i);
							break;
						}
					}
					deliveryHxId = CollUtil.join(idList, ",");
				}
				salesDelivery.setHxType(hxStatus);
//				BigDecimal deliveryHxPrice = salesDelivery.getHxPrice() == null ? BigDecimal.ZERO : salesDelivery.getHxPrice();
				salesDelivery.setHxPrice(totalWriteAmount);
				salesDelivery.setHxId(deliveryHxId);
				deliveryService.updateById(salesDelivery);
				//销售订单状态添加
				String orderHxId = shoporder.getHxId();
				if(StringUtils.isNotBlank(orderHxId)) {
					String[] strs = orderHxId.split(",");
					List<String> idList = CollUtil.newArrayList(strs);
					for (int i = 0; i < idList.size(); i++) {
						String str = idList.get(i);
						if(str.equals(receiptId)) {
							idList.remove(i);
							break;
						}
					}
					orderHxId = CollUtil.join(idList, ",");
				}
                shoporder.setHxPrice(totalWriteAmount.toPlainString());
                shoporder.setOrderHxStatus(hxStatus);
                shoporder.setHxId(orderHxId);
                shoporderService.updateById(shoporder);
				this.deliveryService.updateById(salesDelivery);
			}
		}
		//删除所有的lk信息
		entryLkService.removeByIds(oldLkIdList);
//		//删除添加的核销单信息
//		delivery.setHxId(receipt.getId());
		
		String customerId = vo.getCustomerId();
		BasCustomer basCustomer = customerService.getById(customerId);
		String cusName = "";
		if (basCustomer != null) {
			cusName = basCustomer.getName();
		}
		receipt.setCustomerName(cusName);
		receipt.setPrice(price);
		receipt.setId(receiptId);
		receipt.setIsHx(vo.getIsHX().toString());
		receipt.setCustomerId(customerId);
		receipt.setAccountId(vo.getAccountId());
		String receiveTimeStr = vo.getReceiveTime();
		Date receiveTime = null;
		if(StringUtils.isBlank(receiveTimeStr)) {
			receiveTime = DateUtil.date();
		} else {
			receiveTime = DateUtil.parseDate(receiveTimeStr);
		}
		receipt.setReceiveTime(receiveTime);
		BigDecimal discountPrice = vo.getDiscountPrice();
		receipt.setDiscountPrice(discountPrice);
		receipt.setClearingForm(vo.getClearingForm());
		receipt.setRemark(vo.getRemark());
		
		updateById(receipt);
		if(entryTotalMoney.compareTo(BigDecimal.ZERO) > 0) {
			Map<String, SalesDelivery> theDeliveryMap = Maps.newHashMap();
			//给别的单子结算之后剩下的钱数
			BigDecimal residueEntryAmount = NumberUtil.add(BigDecimal.ZERO, receiptPrice);
			boolean flag = false;
			//给每个收货单明细的结算金额和结算状态赋值
			for(SalesDeliveryEntry entry: entrys) {
				BigDecimal totalPrice = entry.getTotalPrice();
				BigDecimal writeAmount = entry.getWriteAmount();
				if(null == writeAmount) {
					writeAmount = BigDecimal.ZERO;
				}
				BigDecimal addAmount = totalPrice.subtract(writeAmount);
				BigDecimal entryPrice = BigDecimal.ZERO;
				if(residueEntryAmount.compareTo(addAmount) > 0) {
					residueEntryAmount = residueEntryAmount.subtract(addAmount);
					entry.setWriteAmount(totalPrice);
					entry.setWriteStatus("2");
					entryPrice = addAmount;
				} else if(residueEntryAmount.compareTo(addAmount) == 0) {
					residueEntryAmount = residueEntryAmount.subtract(addAmount);
					entry.setWriteAmount(totalPrice);
					entry.setWriteStatus("2");
					entryPrice = addAmount;
					flag = true;
				} else {
					entryPrice = residueEntryAmount;
					entry.setWriteStatus("1");
					entry.setWriteAmount(residueEntryAmount.add(writeAmount));
					flag = true;
				}
				this.entryService.updateById(entry);
				
				//添加一条收款单与发货明细的关联信息
				FinaReceiptEntryLk lk = new FinaReceiptEntryLk();
				lk.setEntryId(entry.getId());
				lk.setEntryStatus(entry.getWriteStatus());
				lk.setAmount(entryPrice);
				lk.setDeliveryId(entry.getDeliveryId());
				lk.setReceiptId(receipt.getId());
				this.entryLkService.save(lk);
				
				//发货单的总金额计算
				String deliveryId = entry.getDeliveryId();
				SalesDelivery delivery = theDeliveryMap.get(deliveryId);
				if(null == delivery) {
					delivery = new SalesDelivery();
					delivery.setId(deliveryId);
					delivery.setTotalAmount(entryPrice);
					theDeliveryMap.put(deliveryId, delivery);
				} else {
					BigDecimal totalAmount = delivery.getTotalAmount();
					if(null == totalAmount) {
						totalAmount = BigDecimal.ZERO;
					}
					totalAmount = totalAmount.add(entryPrice);
					delivery.setTotalAmount(totalAmount);
				}
				if(flag) {
					break;
				}
			}
			//遍历发货单，修改发货单的收款状况
			Map<String, SalesDelivery> deliveryMap = Maps.newHashMap();
			for(SalesDelivery delivery : deliverys) {
				deliveryMap.put(delivery.getId(), delivery);
			}
			//TODO
			for(String key : theDeliveryMap.keySet()) {
				SalesDelivery salesDelivery = deliveryMap.get(key);
				if(null != salesDelivery) {
					String deliveryId = salesDelivery.getId();
					ZrkShoporder shoporder = shoporderService.selectByOrderCode(salesDelivery.getSourceCode());
					List<SalesDeliveryEntry> entryList = deliveryEntryService.lambdaQuery().eq(SalesDeliveryEntry::getDeliveryId, deliveryId).list();
					BigDecimal totalWriteAmount = BigDecimal.ZERO;
					//TODO
					int status0Count = 0;
					int status1Count = 0;
					int status2Count = 0;
					for (SalesDeliveryEntry entry : entryList) {
						String writeStatus = entry.getWriteStatus();
						BigDecimal writeAmount = entry.getWriteAmount();
						if(null == writeStatus) {
							writeStatus = "0";
						}
						if(null == writeAmount) {
							writeAmount = BigDecimal.ZERO;
						}
						totalWriteAmount = totalWriteAmount.add(writeAmount);
						if("2".equals(writeStatus)) {
							status2Count ++;
						}
						if("1".equals(writeStatus)) {
							status1Count ++;
						}
						if("0".equals(writeStatus)) {
							status0Count ++;
						}
					}
					String hxStatus = StringUtils.EMPTY;
					if((status0Count > 0 || status1Count > 0) && status2Count > 0) {
						hxStatus = "1";
					}
					else if(status0Count > 0 && status1Count == 0 && status2Count == 0) {
						hxStatus = "0";
					}
					else if(status0Count == 0 && status1Count > 0 && status2Count == 0) {
						hxStatus = "1";
					}
					else if(status0Count == 0 && status1Count == 0 && status2Count > 0) {
						hxStatus = "2";
					}
					else if(status0Count > 0 && status1Count > 0 && status2Count == 0) {
						hxStatus = "1";
					}
					String deliveryHxId = salesDelivery.getHxId();
					if(StringUtils.isBlank(deliveryHxId)) {
						deliveryHxId = receiptId;
					} else {
						deliveryHxId = deliveryHxId + "," + receiptId;
					}
					salesDelivery.setHxType(hxStatus);
//					BigDecimal deliveryHxPrice = salesDelivery.getHxPrice() == null ? BigDecimal.ZERO : salesDelivery.getHxPrice();
					salesDelivery.setHxPrice(totalWriteAmount);
					salesDelivery.setHxId(deliveryHxId);
					deliveryService.updateById(salesDelivery);
					//销售订单状态添加
					String orderHxId = shoporder.getHxId();
					if(StringUtils.isBlank(orderHxId)) {
						orderHxId = receiptId;
					} else {
						orderHxId = orderHxId + "," + receiptId;
					}
//					String orderHxPriceStr = shoporder.getHxPrice();
//					BigDecimal orderHxPrice = StringUtils.isBlank(orderHxPriceStr) ? BigDecimal.ZERO : new BigDecimal(orderHxPriceStr);
//					orderHxPrice = orderHxPrice.add(totalWriteAmount);
                    shoporder.setHxPrice(totalWriteAmount.toPlainString());
                    shoporder.setOrderHxStatus(hxStatus);
                    shoporder.setHxId(orderHxId);
                    shoporderService.updateById(shoporder);
					this.deliveryService.updateById(salesDelivery);
				}
			}
		}
		
		//添加一个发货单信息
		SalesDelivery delivery = this.deliveryService.lambdaQuery().eq(SalesDelivery::getHxId, receiptId).one();
		if(null != delivery) {
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			delivery.setCode(receipt.getCode());
			delivery.setHxPrice(receipt.getPrice());
			delivery.setZkPrice(receipt.getDiscountPrice());
			delivery.setCustomerId(receipt.getCustomerId());
			delivery.setCustomerName(cusName);
			delivery.setShippingDate(receiveTime);
			delivery.setSalesType(1);
			delivery.setMaker(sysUser.getRealname());
			BasCustomerAddress customAddress = addressService.getCustomAddress(customerId);
			if (customAddress != null) {
				delivery.setCustomerAddress(customAddress.getAddress());
				delivery.setCustomerPhone(customAddress.getPhoneNo());
			}
			delivery.setHxId(receipt.getId());
			deliveryService.updateById(delivery);// 添加发货单收款信息
			String dId = delivery.getId();
			SalesDeliveryEntry entry = this.deliveryEntryService.lambdaQuery().eq(SalesDeliveryEntry::getDeliveryId, dId).one();
			if(null != entry) {
				String dictName = sysBasApi.queryDictTextByKey("clearingForm", receipt.getClearingForm());
				entry.setProductName(dictName);
				entry.setCustomerId(delivery.getCustomerId());
				entry.setDeliveryId(delivery.getId());
				deliveryEntryService.updateById(entry);// 保存发货单收款明细---其实基本就一个结算方式~~
			}
		}
		
		return Result.ok("编辑成功");
	}


	@Override
	public Result<ReceiptVO> getReceiptInfo(String receiptId) {
		// TODO Auto-generated method stub
		Result<ReceiptVO> result = new Result<>();
		FinaReceipt receipt = this.getById(receiptId);
		ReceiptVO dto = new ReceiptVO();
		if(null != receipt) {
			String accountId = receipt.getAccountId();
			dto.setAccountId(accountId);
			if(StringUtils.isNotBlank(accountId)) {
				BasBankAccount account = this.accountService.getById(accountId);
				dto.setAccountNo(account.getAccountNo());
			}
			dto.setId(receipt.getId());
			dto.setClearingForm(receipt.getClearingForm());
			dto.setCustomerId(receipt.getCustomerId());
			dto.setDiscountPrice(receipt.getDiscountPrice());
			dto.setRemark(receipt.getRemark());
			dto.setIsHX(Boolean.valueOf(receipt.getIsHx()));
			Date receiveTime = receipt.getReceiveTime();
			if(null != receiveTime) {
				dto.setReceiveTime(DateUtil.formatDate(receiveTime));
			}
			dto.setPrice(receipt.getPrice());
			dto.setCustomerName(receipt.getCustomerName());
			List<FinaReceiptEntryLk> list = this.entryLkService.lambdaQuery().eq(FinaReceiptEntryLk::getReceiptId, receiptId).list();
			List<String> entryIdList = Lists.newArrayList();
			Map<String, FinaReceiptEntryLk> lkMap = Maps.newHashMap();
			if(CollUtil.isNotEmpty(list)) {
				for (FinaReceiptEntryLk lk : list) {
					entryIdList.add(lk.getEntryId());
					lk.setId(lk.getEntryId());
					lkMap.put(lk.getEntryId(), lk);
				}
			}
			dto.setLkList(list);
			String customerId = receipt.getCustomerId();
			List<DeliveryDTO> deliverys = this.getCustomerDelivery(customerId, entryIdList, receiptId);
			List<DeliveryDTO> resultList = Lists.newArrayList();
			List<DeliveryDTO> selectList = Lists.newArrayList();
			List<DeliveryDTO> unSelectList = Lists.newArrayList();
			if(CollUtil.isNotEmpty(deliverys)) {
				for (DeliveryDTO dd : deliverys) {
					if(entryIdList.contains(dd.getId())) {
						FinaReceiptEntryLk lk = lkMap.get(dd.getId());
						if(null != lk) {
							dd.setEntryAmount(lk.getAmount());
						}
						dd.setSelect(true);
						selectList.add(dd);
					} else {
						dd.setSelect(false);
						dd.setEntryAmount(BigDecimal.ZERO);
						unSelectList.add(dd);
					}
				}
				resultList.addAll(selectList);
				resultList.addAll(unSelectList);
			}
			if(CollUtil.isNotEmpty(list)) {
				for (FinaReceiptEntryLk lk : list) {
					entryIdList.add(lk.getEntryId());
					lk.setId(lk.getEntryId());
				}
			}
			dto.setEntryIdList(resultList);
		}
		result.setResult(dto);
		return result;
	}
	
	private List<DeliveryDTO> getCustomerDelivery(String customerId, List<String> entryIdList, String receiptId) {
		List<DeliveryDTO> dtos = this.baseMapper.getDeliveryEntryAndId(customerId, entryIdList);
		List<FinaReceiptEntryLk> list = this.entryLkService.lambdaQuery().eq(FinaReceiptEntryLk::getReceiptId, receiptId).list();
		Map<String, FinaReceiptEntryLk> lkMap = Maps.newHashMap();
		if(CollUtil.isNotEmpty(list)) {
			for (FinaReceiptEntryLk lk : list) {
				lkMap.put(lk.getEntryId(), lk);
			}
		}
		if(CollUtil.isNotEmpty(dtos)) {
			BigDecimal sum = BigDecimal.ZERO;
			for (DeliveryDTO dto : dtos) {
				BigDecimal unPayAmount = dto.getUnPayAmount();
				if(null == unPayAmount) {
					unPayAmount = BigDecimal.ZERO;
				}
				FinaReceiptEntryLk lk = lkMap.get(dto.getId());
				if(lk != null && lk.getAmount() != null) {
					sum = sum.add(lk.getAmount());
				}
				sum = sum.add(unPayAmount);
				dto.setSummary(sum);
			}
		}
		return dtos;
	}
	
	@Override
	public Result<?> getCustomerDelivery(String customerId) {
		List<DeliveryDTO> dtos = this.baseMapper.getDeliveryEntry(customerId);
		if(CollUtil.isNotEmpty(dtos)) {
			BigDecimal sum = BigDecimal.ZERO;
			for (DeliveryDTO dto : dtos) {
				BigDecimal unPayAmount = dto.getUnPayAmount();
				if(null == unPayAmount) {
					unPayAmount = BigDecimal.ZERO;
				}
				dto.setEntryAmount(BigDecimal.ZERO);
				sum = sum.add(unPayAmount);
				dto.setSummary(sum);
			}
		}
		return Result.ok(dtos);
	}

	@Override
	public FinaReceiptPrintDTO getSalesDeliveryByTime(FinaReceiptPage vo) {
		// TODO Auto-generated method stub
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendarEnd = Calendar.getInstance();
		try {
			calendarEnd.setTime(format.parse(vo.getCreateTimeEnd()));
			calendarEnd.set(Calendar.HOUR_OF_DAY, 23);
			calendarEnd.set(Calendar.MINUTE, 59);
			calendarEnd.set(Calendar.SECOND, 59);
			//防止mysql自动加一秒,毫秒设为0
			calendarEnd.set(Calendar.MILLISECOND, 0);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		//根据前端传进来的筛选条件，查询收款单数据
		LambdaQueryWrapper<FinaReceipt> queryWrapper = new LambdaQueryWrapper<FinaReceipt>();
		queryWrapper.eq(FinaReceipt::getCustomerId, vo.getCustomerId());
		queryWrapper.between(FinaReceipt::getCreateTime, vo.getCreateTimeStart(), calendarEnd.getTime());
		List<FinaReceipt> list = this.baseMapper.selectList(queryWrapper);
		BigDecimal hdPrice = BigDecimal.ZERO;//货单金额
		BigDecimal skPrice = BigDecimal.ZERO;//收款金额
		BigDecimal zkPrice = BigDecimal.ZERO;//折扣金额
		BigDecimal qcPrice = BigDecimal.ZERO;//期初欠款
		BigDecimal ysPrice = BigDecimal.ZERO;//应收余额
		String customerName = "";
		if(list!=null && list.size()>0) {
			for(FinaReceipt fina:list) {
				if(oConvertUtils.isNotEmpty(fina.getPrice())) {
					if(StringUtils.equals(fina.getBillType(), "1")) {
						hdPrice = hdPrice.add(fina.getPrice());
					}
					if(StringUtils.equals(fina.getBillType(), "2")) {
						skPrice = skPrice.add(fina.getPrice());
					}
				}
				if(oConvertUtils.isNotEmpty(fina.getDiscountPrice())) {
					zkPrice = zkPrice.add(fina.getDiscountPrice());
				}
				if(oConvertUtils.isEmpty(customerName)) {
					customerName = fina.getCustomerName();
				}
			}
		}
		//查询期初欠款
		FinaReceiptPage receiptPage = baseMapper.getTotalOwed(vo.getCustomerId(), vo.getCustomerName(), vo.getCreateTimeStart());
		if(receiptPage!=null && oConvertUtils.isNotEmpty(receiptPage.getTotalOwed())) {
			qcPrice = receiptPage.getTotalOwed();
		}
		ysPrice = qcPrice.add(hdPrice).subtract(skPrice).subtract(zkPrice);
		FinaReceiptPrintDTO dto = new FinaReceiptPrintDTO();
		String totalBig ="";
		dto.setCustomerName(customerName);
		dto.setTotalAmount(ysPrice);
		totalBig = ZrkDeliverEntryServiceImpl.toChinese(ysPrice.toString());
		dto.setTotalBig(totalBig);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		dto.setShippingDate(formatter.format(new Date()));
//		StringBuffer buffer = new StringBuffer();
//        String[] s = vo.getCreateTimeEnd().split("-");
//        buffer.append(s[0]);
//        buffer.append("年");
//        buffer.append(s[1]);
//        buffer.append("月");
//        buffer.append(s[2]);
//        buffer.append("日");
//		dto.setCreateTimeEnd(buffer.toString());
		formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = formatter.parse(vo.getCreateTimeEnd());
			formatter = new SimpleDateFormat("yyyy年MM月dd日");
			dto.setCreateTimeEnd(formatter.format(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dto;
	}


	@Override
	public boolean printChargeTime(FinaReceiptPage receipt) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		BasCustomer basCustomer = customerService.getById(receipt.getCustomerId());
		try {
			basCustomer.setChargeTimeStart(formatter.parse(receipt.getCreateTimeStart()));
			basCustomer.setChargeTimeEnd(formatter.parse(receipt.getCreateTimeEnd()));
			return customerService.updateById(basCustomer);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return false;
	}
}
